package com.jishuo.nontax.bfc.pzk;

import com.jishuo.base.service.SequenceService;
import com.jishuo.base.util.GTimeUtil;
import com.jishuo.base.util.GsonUtil;
import com.jishuo.nontax.bean.vo.PzmsgVO;
import com.jishuo.nontax.bfc.dao.PzkMessageMapper;
import lombok.extern.slf4j.Slf4j;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.StringWriter;

/**
 * 发送数据到凭证库
 * 凭证先入库，使用定时任务定时查库发送凭证库系统
 */
@Slf4j
@Service
public class PzkService {

    @Resource
    private PzkMessageMapper pzkMessageMapper;
    @Resource
    private SequenceService sequenceService;

    /**
     * 保存凭证
     * @param action 消息
     * @param objData 数据
     * @return
     */
    public int savePzmsg(String action, Object objData) {
        try {
            PzmsgVO vo = new PzmsgVO();
            vo.setAction(action);
            vo.setData(GsonUtil.fromObjectToJson(objData));
            vo.setAddtime(GTimeUtil.getDateTimeMark());
            vo.setState(1);
            vo.setDataid(sequenceService.getNextSeq("PZMESSAGESEQ"));
            return pzkMessageMapper.savePzmsg(vo);
        } catch (Exception e) {
            log.info("凭证数据解析异常", e);
            return 0;
        }
    }

    /**
     * 保存冲销消息
     * @param billType 票据类型
     * @param billNum 缴款码
     * @param bankAffirm 核心流水
     * @return
     */
    public int savePzmsgOut(int billType, String billNum, String bankAffirm) {
        try {
            PzmsgVO vo = new PzmsgVO();
            vo.setAction("setBillBackOut");
            vo.setData("{\"billtype\": " + billType + ",\"billnum\": \"" + billNum + "\",\"bankaffirm\": \"" + bankAffirm + "\"}");
            vo.setAddtime(GTimeUtil.getDateTimeMark());
            vo.setState(1);
            vo.setDataid(sequenceService.getNextSeq("PZMESSAGESEQ"));
            return pzkMessageMapper.savePzmsg(vo);
        } catch (Exception e) {
            log.info("凭证数据解析异常", e);
            return 0;
        }
    }
    /**
     * 发送数据到凭证库
     * @param head 报文头
     * @param objData 数据对象
     * @return 0 - 成功
     */
    public static int sendPzk(String head, Object objData) {
        try {
            //xml解析器
            Serializer serializer = new Persister();
            //xml转换器
            StringWriter sw = new StringWriter();
            serializer.write(objData, sw);
            String orgdata = sw.toString();

            String content = "<root><head>" + head + "</head><body><voucher>" + orgdata + "</voucher></body></root>";
            PzkSocketClient socket=new PzkSocketClient();
            socket.Client(content);

        } catch (Exception e) {
            log.info("发送凭证库失败。" + e.toString());
            return 101;
        }

        return 0;
    }
}
